package com.example.myproject.utils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class BencodeUtils {

    // 查找 "info" 开始位置（返回的是 value 的起始 index）
    public static int findInfoStart(byte[] bytes) {
        byte[] infoKey = "4:info".getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < bytes.length - infoKey.length; i++) {
            if (matchBytes(bytes, i, infoKey)) {
                return i + infoKey.length; // 紧随其后的就是 "info" 对应 value 的开始
            }
        }
        throw new IllegalArgumentException("未找到 info 字段");
    }

    // 查找 info 字段的结尾位置（基于 bencode 解码规则，假设 info 是一个字典 d...e）
    public static int findInfoEnd(byte[] bytes, int infoStart) {
        int pos = infoStart;
        int depth = 0;

        if (bytes[pos] != 'd') {
            throw new IllegalArgumentException("info 字段应以 'd' 开头");
        }

        depth++;
        pos++;

        while (pos < bytes.length && depth > 0) {
            byte b = bytes[pos];

            if (b == 'd' || b == 'l') {
                depth++;
                pos++;
            } else if (b == 'e') {
                depth--;
                pos++;
            } else if (b >= '0' && b <= '9') {
                // 字符串长度解析
                int len = 0;
                while (bytes[pos] >= '0' && bytes[pos] <= '9') {
                    len = len * 10 + (bytes[pos] - '0');
                    pos++;
                }

                if (pos >= bytes.length || bytes[pos] != ':') {
                    throw new IllegalArgumentException("字符串长度后应为 ':'，但未找到");
                }

                pos++; // 跳过 ':'
                pos += len; // 跳过内容

                if (pos > bytes.length) {
                    throw new IllegalArgumentException("字符串超出数据范围");
                }
            } else if (b == 'i') {
                pos++;
                while (bytes[pos] != 'e') {
                    if (bytes[pos] < '0' || bytes[pos] > '9') {
                        throw new IllegalArgumentException("整数格式非法");
                    }
                    pos++;
                }
                pos++; // 跳过 'e'
            } else {
                throw new IllegalArgumentException("未知 bencode 类型: pos=" + pos + ", byte=" + (char) b);
            }
        }

        if (depth != 0) {
            throw new IllegalArgumentException("bencode 解码 info 时嵌套不匹配，depth=" + depth);
        }

        return pos;
    }


    // 替换 encoded 数据中的 info 字段为原始 infoBytes
    public static byte[] replaceInfoSection(byte[] encoded, byte[] rawInfoBytes) {
        int infoStart = findInfoStart(encoded);
        int infoEnd = findInfoEnd(encoded, infoStart);

        byte[] prefix = Arrays.copyOfRange(encoded, 0, infoStart);
        byte[] suffix = Arrays.copyOfRange(encoded, infoEnd, encoded.length);

        byte[] finalBytes = new byte[prefix.length + rawInfoBytes.length + suffix.length];
        System.arraycopy(prefix, 0, finalBytes, 0, prefix.length);
        System.arraycopy(rawInfoBytes, 0, finalBytes, prefix.length, rawInfoBytes.length);
        System.arraycopy(suffix, 0, finalBytes, prefix.length + rawInfoBytes.length, suffix.length);

        return finalBytes;
    }

    // 判断从 offset 开始的字节是否与目标 byte 数组匹配
    private static boolean matchBytes(byte[] source, int offset, byte[] target) {
        if (offset + target.length > source.length) return false;
        for (int i = 0; i < target.length; i++) {
            if (source[offset + i] != target[i]) return false;
        }
        return true;
    }
}
